package top.igotcha.chapter.chapter3.threadRunningOrder;

/**
 * @author Gotcha
 * @date 2021/3/8
 * @describe 固定运行顺序,Wait/Notify版
 */
public class WaitNotify {
    static Object lock = new Object();
    static boolean startFromT1 = true;
    public static void main(String[] args) {

        Thread t1 = new Thread(()->{
            synchronized (lock){
                while (!startFromT1){
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("线程t1开始运行");
                startFromT1 = !startFromT1;
                lock.notifyAll();
            }
        },"t1");

        Thread t2 = new Thread(()->{
            synchronized (lock){
                while (startFromT1){
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("线程t2开始运行");
                startFromT1 = !startFromT1;
                lock.notifyAll();
            }
        },"t2");

        t1.start();
        t2.start();
    }
}
